<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\index\controller;

use service\DataService;
use service\WechatService;
use think\Controller;
use QL\QueryList;
use think\view\driver\Think;
use think\Db;

//use think\Facade\Session;
use think\Session;

/**
 * 应用入口控制器1
 * @author Anyon <zoujingli@qq.com>
 */
class Index extends Base
{


    public function index(){
        $first_leader = input('first_leader');

        //查询用户上级信息
        if (isset($first_leader) && $first_leader != '') {
            $leaderInfo = Db::name('store_member')->where(['openid' => $first_leader])->find();
            $shop_id = $leaderInfo['shop_id'];
            if (!$leaderInfo) $this->error('当前二维码已失效');
//            Cache('leaderInfo', $leaderInfo);
        }
        //根据上级用户查找维修厂
        if (isset($shop_id) && $shop_id != '') {
            $shopInfo = Db::name('store_shops')->where(['id' => $shop_id])->find();
            if (!$shopInfo) $this->error('当前二维码已失效');
        }

        //查询用户信息
        $fans = WechatService::webOauth($this->request->url(true), 1);
        if (!empty($fans)){
            $fansInfo = WechatService::WeChatUser()->getUserInfo($fans['openid']);
            $userInfo = Db::name('store_member')->where('openid',$fans['openid'])->find();
            if(!$fansInfo) $this->error('授权失败');


            $this->updateUserInfo(['openid'=>$fansInfo['openid']],['subscribe'=>$fansInfo['subscribe']]);
            if (!empty($userInfo)){
                $url = "http://" . $_SERVER['HTTP_HOST'] . '/system/#/?wx_token=' . $userInfo['wx_token'];
                header("Location:" . $url);
            }else{
                //用户注册
                $fansInfo = $fans['fansinfo'];
                $wxtoken = $this->getToken();
                $insertData = [
                    'openid' => $fansInfo['openid'],
                    'nickname' => $fansInfo['nickname'],
                    'sex' => $fansInfo['sex'],
                    'headimg' => $fansInfo['headimgurl'],
                    'wx_token' => $wxtoken,
                ];
                if (!empty($shop_id)){
                    $insertData['shop_id'] = $shop_id;
                }else{
                    $insertData['shop_id'] = 0;
                }
                Db::startTrans();
                $res['userid'] = Db::name('store_member')->insertGetId($insertData);
                if (!empty($leaderInfo)) {
                    \think\facade\Hook::listen('AssocUserParent', ['user_id' => $res['userid'], 'parent_id' => $leaderInfo['id']]);
                }
                if (check_arr($res)){
                    Db::commit();
                    $url = "http://" . $_SERVER['HTTP_HOST'] . '/system/#/?wx_token=' . $wxtoken;
                    header("Location:" . $url);
                }else{
                    Db::rollback();
                }
            }
        }
    }




    public function updateUserInfo($where= [],$data =[]){
        return Db::name('store_member')->where($where)->update($data) !== FALSE;
    }

    public function shopsaddmember()
    {
        $fans = WechatService::webOauth($this->request->url(true), 1);

//        $fansInfo = WechatService::WeChatUser()->getUserInfo($fans['openid']);
        $userInfo = Db::name('store_member')->where(['openid' => $fans['openid']])->find();
        $shop_id = input('shop_id');
        if (!$userInfo || $userInfo == null){
            $fansInfo = $fans['fansinfo'];
            $wxtoken = $this->getToken();
            $insertData = [
                'openid' => $fansInfo['openid'],
                'nickname' => $fansInfo['nickname'],
                'sex' => $fansInfo['sex'],
                'headimg' => $fansInfo['headimgurl'],
                'wx_token' => $wxtoken,
            ];
            if (isset($shop_id) || $shop_id !== ''){
                $insertData['shop_id'] = $shop_id;
            }else{
                $insertData['shop_id'] = 0;
            }
            Db::startTrans();
            $res['userid'] = Db::name('store_member')->insertGetId($insertData);
            if (check_arr($res)) {
                Db::commit();
                $url = "http://" . $_SERVER['HTTP_HOST'] . '/system#/?wx_token=' . $wxtoken;
                header("Location:" . $url);
            } else {
                Db::rollback();
                $this->error('网络故障,授权失败');
            }
        }
        if($userInfo['shop_id']==0)
        {
            Db::name('store_member')->where(['id' => $userInfo['id']])->update(['shop_id' => $shop_id]);

        }
        $userInfo = Db::name('store_member')->order('id desc')->find();
        $url = "http://" . $_SERVER['HTTP_HOST'] . '/system/#/?wx_token=' . $userInfo['wx_token'];
        header("Location:" . $url);
    }

    public function getToken()
    {
        $v = 1;
        $key = mt_rand();
        $hash = hash_hmac("sha1", $v . mt_rand() . get_time(), $key, true);
        $token = str_replace('=', '', strtr(base64_encode($hash), '+/', '-_'));
        return $token;
    }


}
